package com.example.demo.controller;

import com.example.demo.common.AjaxResult;
import com.example.demo.common.UserSessionUtils;
import com.example.demo.entity.Articleinfo;
import com.example.demo.entity.BlogRecycle;
import com.example.demo.entity.Userinfo;
import com.example.demo.service.ArticleService;
import com.example.demo.service.BlogRecycleService;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/art")
public class ArticleController {
    private static Logger log= Logger.getLogger(ArticleController.class);

    @Autowired
    private ArticleService articleService;

    @Autowired
    private BlogRecycleService blogRecycleService;


    @RequestMapping("/mylist")
    public AjaxResult getMyList(HttpServletRequest request){
        Userinfo userinfo = UserSessionUtils.getUser(request);
        if(userinfo == null){
            return AjaxResult.fail(-1,"非法请求");
        }
        List<Articleinfo> list = articleService.getMyList(userinfo.getId());

        //自己实现的
        //对于 content 的设置
        for (Articleinfo articleinfo:list) {
            articleinfo.setContent(articleinfo.getContent().
                    replaceAll("#",""));
            articleinfo.setContent(articleinfo.getContent().
                    replaceAll("%",""));
            articleinfo.setContent(articleinfo.getContent().
                    replaceAll("## ",""));
            if(articleinfo.getContent().length()>15){
                articleinfo.setContent(articleinfo.getContent().substring(0,9));
            }
        }

        return AjaxResult.success(list);
    }

    /**
     * 个人页面删除文章
     * @param id
     * @param request
     * @return
     */
    @RequestMapping("/del")
    public AjaxResult del(Integer id,HttpServletRequest request){
        if(id == null || id <= 0){
            //参数有误
            return AjaxResult.fail(-1,"参数异常");
        }

        Userinfo userinfo = UserSessionUtils.getUser(request);
        if(userinfo == null){
            return  AjaxResult.fail(-2,"用户未登录");
        }

        Articleinfo articleinfo = articleService.getById(id, userinfo.getId());
        BlogRecycle blogRecycle = new BlogRecycle();

        blogRecycle.setId(id);
        blogRecycle.setUid(userinfo.getId());
        blogRecycle.setCreatetime(articleinfo.getCreatetime());
        blogRecycle.setUpdatetime(articleinfo.getUpdatetime());
        blogRecycle.setTitle(articleinfo.getTitle());
        blogRecycle.setContent(articleinfo.getContent());
        blogRecycle.setRcount(articleinfo.getRcount());
        blogRecycle.setState(articleinfo.getState());

        blogRecycleService.add(blogRecycle);

        return AjaxResult.success(articleService.del(id,userinfo.getId()));
    }

    /**
     * 返回文章参数 前端从而得到详细文章信息
     * @param id
     * @return
     */
    @RequestMapping("/detail")
    public AjaxResult getDetail(Integer id){
        if(id == null || id <= 0){
            return AjaxResult.fail(-1,"非法参数");
        }
        return AjaxResult.success(articleService.getDetail(id));
    }

    @RequestMapping("/increment-rcount")
    public AjaxResult incrementRCount(Integer id){
        if(id != null && id > 0){
            return AjaxResult.success(articleService.incrementRCount(id));
        }
        return AjaxResult.success(-1,"未知错误");
    }

    @RequestMapping("/add")
    public AjaxResult add(HttpServletRequest request,Articleinfo articleinfo){
        //1.非空效验
        if(articleinfo==null || !StringUtils.hasLength(articleinfo.getTitle()) ||
        !StringUtils.hasLength(articleinfo.getContent())){
            return AjaxResult.fail(-1,"非法参数");
        }
        //2.数据库添加操作
        //a.得到当前登录用户的 uid
        Userinfo userinfo = UserSessionUtils.getUser(request);
        if(userinfo == null || userinfo.getId() <= 0){
            //无效的登录用户
            return AjaxResult.fail(-1,"非法参数");
        }
        articleinfo.setUid(userinfo.getId());

        //b.添加数据库并返回结果
        return AjaxResult.success(articleService.add(articleinfo));
    }

    @RequestMapping("/update")
    public AjaxResult update(HttpServletRequest request,Articleinfo articleinfo){

        if(articleinfo == null || !StringUtils.hasLength(articleinfo.getTitle())||
        !StringUtils.hasLength(articleinfo.getContent()) || articleinfo.getId() == null){
            return AjaxResult.fail(-1,"非法参数");
        }

        //得到当前登录用户的 id
        Userinfo userinfo = UserSessionUtils.getUser(request);
        if(userinfo == null && userinfo.getId() == null){
            //无效用户
            return AjaxResult.fail(-2,"无效用户");
        }

        //很核心的代码
        //把当前用户的 id 设置到文章 uid 里面，只能通过当前登录用户设置，不能由前端来传
        articleinfo.setUid(userinfo.getId());
        articleinfo.setUpdatetime(LocalDateTime.now());
        log.info("用戶"+userinfo.getUsername()+"修改文章");

        return AjaxResult.success(articleService.update(articleinfo));
    }

    /**
     * 查询列表根据分页
     *
     * @param pindex 当前页码（从1开始）
     * @param psize  每页显示条数
     * @return
     */
    @RequestMapping("/listbypage")
    public AjaxResult getListByPage(Integer pindex, Integer psize){
        //1.参数校正
        if(pindex == null || pindex <= 1){
            pindex = 1;
        }
        if(psize == null || psize <= 1){
            //默认每页显示文章的最小数量
            psize = 2;
        }
        //分页公式的值 = （当前页码-1）*每页显示条数
        int offset = (pindex - 1) * psize;

        // 文章列表数据
        List<Articleinfo> list = articleService.getListByPage(psize, offset);
        // 当前列表总共有多少页
        // a.总共有多少条数据
        int totalCount = articleService.getCount();
        // b.总条数/psize（每页显示条数）
        double pcountdb = totalCount / (psize * 1.0);
        // c.使用进一法得到总页数
        int pcount = (int) Math.ceil(pcountdb);
        HashMap<String, Object> result = new HashMap<>();
        result.put("list", list);
        result.put("pcount", pcount);
        return AjaxResult.success(result);

    }

//    @RequestMapping("/export")
//    public AjaxResult getExportList(HttpServletRequest request,Integer id){
//        Userinfo userinfo = UserSessionUtils.getUser(request);
//        if(userinfo == null || userinfo.getId() <= 0){
//            return AjaxResult.fail(-1,"非法参数");
//        }
//
//        Articleinfo articleinfo = articleService.getById(id,userinfo.getId());
//        return AjaxResult.success(articleinfo);
//    }
    @GetMapping("/export")
    public ResponseEntity<String> export(HttpServletRequest req, HttpServletResponse response, Integer id) throws IOException {
        Userinfo userinfo = UserSessionUtils.getUser(req);
        if(userinfo == null || userinfo.getId() <= 0){
            return ResponseEntity.badRequest().body("非法参数");
        }

        Articleinfo articleinfo = articleService.getById(id,userinfo.getId());
        return ResponseEntity.ok()
                .header("Content-Type","text/plain")
                .body(articleinfo.getContent());
    }

    @RequestMapping("/batchDel")
    public AjaxResult batchDel(HttpServletRequest request,@RequestParam(value = "ids", required = false) Integer[] ids){
//        // 打印所有参数
//        Enumeration<String> parameterNames = request.getParameterNames();
//        while (parameterNames.hasMoreElements()) {
//            String paramName = parameterNames.nextElement();
//            System.out.println("Parameter: " + paramName + " = " + Arrays.toString(request.getParameterValues(paramName)));
//        }

        Userinfo userinfo = UserSessionUtils.getUser(request);
        if(userinfo == null || userinfo.getId() <= 0){
            return AjaxResult.fail(-1,"非法参数");
        }

        return AjaxResult.success(articleService.batchDel(ids,userinfo.getId()));
    }

}
